<template>
  <a-spin
      :loading="spinLoading"
      :size="35"
      class="w-[100%]"
      tip="正在加载, 请稍候..."
  >
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <!-- 基本信息区域 -->
      <div class="mb-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-[var(--color-text-1)]">基本信息</h2>
          <a-space>
            <a-button type="primary" @click="onEdit">
              <icon-edit/>
              编辑
            </a-button>
            <a-button @click="onBack">
              <icon-arrow-left/>
              返回
            </a-button>
          </a-space>
        </div>
        
        <a-descriptions
            :column="3"
            :data="basicInfoData"
            layout="horizontal"
            size="large"
        />
      </div>

      <!-- PDF模板预览区域 -->
      <div class="mb-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-[var(--color-text-1)]">PDF模板</h2>
          <a-space>
            <a-button v-if="templateInfo.pdfUrl" @click="downloadPdf">
              <icon-download/>
              下载模板
            </a-button>
            <a-button v-if="templateInfo.pdfUrl" @click="previewPdf">
              <icon-eye/>
              预览模板
            </a-button>
          </a-space>
        </div>
        
        <div v-if="templateInfo.pdfUrl" class="pdf-container">
          <div class="pdf-info mb-4">
            <a-alert
                :show-icon="false"
                message="PDF模板文件"
                type="info"
            >
              <template #description>
                <div class="flex items-center space-x-4">
                  <span>文件名: {{ templateInfo.pdfFileName }}</span>
                  <span>文件大小: {{ templateInfo.pdfFileSize }}</span>
                  <span>上传时间: {{ templateInfo.uploadTime }}</span>
                </div>
              </template>
            </a-alert>
          </div>
          
          <!-- PDF预览缩略图 -->
          <div class="pdf-thumbnail">
            <div class="border border-gray-300 rounded-lg p-4 bg-gray-50 text-center">
              <icon-file-pdf class="text-6xl text-red-500 mb-2"/>
              <p class="text-gray-600">{{ templateInfo.pdfFileName }}</p>
              <p class="text-sm text-gray-400">点击预览按钮查看完整内容</p>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-pdf">
          <a-empty description="暂无PDF模板文件"/>
        </div>
      </div>

      <!-- 字段配置区域 -->
      <div class="mb-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-[var(--color-text-1)]">字段配置</h2>
          <a-tag :color="templateInfo.fields?.length > 0 ? 'green' : 'orange'">
            共 {{ templateInfo.fields?.length || 0 }} 个字段
          </a-tag>
        </div>
        
        <a-table
            v-if="templateInfo.fields?.length > 0"
            :columns="fieldColumns"
            :data="templateInfo.fields"
            :pagination="false"
            :scroll="{ y: 400 }"
            row-key="id"
        >
          <template #fieldType="{ record }">
            <a-tag :color="getFieldTypeColor(record.fieldType)">
              {{ getFieldTypeText(record.fieldType) }}
            </a-tag>
          </template>
          <template #required="{ record }">
            <a-tag :color="record.required ? 'red' : 'gray'">
              {{ record.required ? '必填' : '选填' }}
            </a-tag>
          </template>
          <template #position="{ record }">
            <span class="font-mono text-sm">
              ({{ record.position.x }}, {{ record.position.y }})
            </span>
          </template>
          <template #defaultValue="{ record }">
            <span class="text-gray-600">
              {{ record.defaultValue || '-' }}
            </span>
          </template>
        </a-table>
        
        <div v-else class="empty-fields">
          <a-empty description="暂无字段配置"/>
        </div>
      </div>

      <!-- 操作日志区域 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4 text-[var(--color-text-1)]">操作日志</h2>
        
        <a-timeline>
          <a-timeline-item
              v-for="log in operationLogs"
              :key="log.id"
              :dot-color="getLogDotColor(log.type)"
          >
            <template #dot>
              <icon-check-circle v-if="log.type === 'create'"/>
              <icon-edit v-else-if="log.type === 'update'"/>
              <icon-eye v-else-if="log.type === 'view'"/>
              <icon-download v-else-if="log.type === 'download'"/>
            </template>
            <div class="flex items-center justify-between">
              <div>
                <div class="font-medium">{{ log.action }}</div>
                <div class="text-sm text-gray-500 mt-1">
                  操作人: {{ log.operator }} | 时间: {{ log.time }}
                </div>
                <div v-if="log.remark" class="text-sm text-gray-400 mt-1">
                  备注: {{ log.remark }}
                </div>
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>
    </div>

    <!-- PDF预览弹窗 -->
    <a-modal
        v-model:visible="pdfPreviewVisible"
        :footer="false"
        :width="900"
        title="PDF模板预览"
    >
      <div class="pdf-preview-container">
        <iframe
            v-if="templateInfo.pdfUrl"
            :src="templateInfo.pdfUrl"
            class="w-full h-[600px] border-0"
        ></iframe>
      </div>
    </a-modal>
  </a-spin>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, watch} from "vue";
import {
  IconEdit,
  IconArrowLeft,
  IconDownload,
  IconEye,
  IconFilePdf,
  IconCheckCircle,
  IconPlus
} from "@arco-design/web-vue/es/icon";
import {
  getContractTemplateByContractTemplateIdApi
} from "~/api/lindi/contractTemplate";

// 全局实例
const {proxy} = getCurrentInstance();

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emit
const emit = defineEmits(["edit", "back"]);

// 加载状态
const spinLoading = ref(false);

// PDF预览相关
const pdfPreviewVisible = ref(false);

// 模板信息
const templateInfo = reactive({
  contractTemplateId: "",
  contractTemplateName: "",
  contractTemplateType: "",
  status: "",
  contractDescription: "",
  pdfUrl: "",
  pdfFileName: "",
  pdfFileSize: "",
  uploadTime: "",
  fields: [],
  createTime: "",
  updateTime: "",
  creator: "",
  updater: ""
});

// 基本信息数据
const basicInfoData = ref([]);

// 操作日志
const operationLogs = ref([]);

// 字段表格列配置
const fieldColumns = [
  {title: "字段名称", dataIndex: "fieldName", width: 150},
  {title: "字段标识", dataIndex: "fieldKey", width: 150},
  {title: "字段类型", dataIndex: "fieldType", slotName: "fieldType", width: 120},
  {title: "必填", dataIndex: "required", slotName: "required", width: 80, align: "center"},
  {title: "默认值", dataIndex: "defaultValue", slotName: "defaultValue", width: 120},
  {title: "页码", dataIndex: "pageNumber", width: 80, align: "center"},
  {title: "位置坐标", dataIndex: "position", slotName: "position", width: 150, align: "center"},
];

// 监听参数变化
watch(
    () => props.params,
    () => {
      if (props.params.contractTemplateId) {
        loadTemplateDetail(props.params.contractTemplateId);
      }
    },
    {deep: true, immediate: true}
);

// 加载模板详情
function loadTemplateDetail(contractTemplateId) {
  spinLoading.value = true;
  
  getContractTemplateByContractTemplateIdApi(contractTemplateId)
    .then(res => {
        Object.assign(templateInfo, res);
        
        // 构建基本信息数据
        basicInfoData.value = [
          {label: "模板名称", value: templateInfo.contractTemplateName},
          {label: "模板类型", value: getTemplateTypeText(templateInfo.contractTemplateType)},
          {label: "状态", value: getStatusText(templateInfo.status)},
          {label: "创建时间", value: templateInfo.createTime},
          {label: "更新时间", value: templateInfo.updateTime},
          {label: "创建人", value: templateInfo.creator},
          {label: "更新人", value: templateInfo.updater},
          {label: "字段数量", value: `${templateInfo.fields?.length || 0} 个`},
          {label: "描述", value: templateInfo.contractDescription || '-', span: 3}
        ];
        
        // 模拟操作日志 - 实际项目中应该从后端获取
        operationLogs.value = [
          {
            id: 1,
            type: "create",
            action: "创建合同模板",
            operator: templateInfo.creator || "系统",
            time: templateInfo.createTime,
            remark: "初始创建"
          },
          {
            id: 2,
            type: "update",
            action: "更新模板信息",
            operator: templateInfo.updater || "系统",
            time: templateInfo.updateTime,
            remark: "最近更新"
          },
          {
            id: 3,
            type: "view",
            action: "查看模板详情",
            operator: "当前用户",
            time: new Date().toLocaleString(),
            remark: ""
          }
        ];
    })
    .catch(error => {
      console.error('加载模板详情失败:', error);
      proxy.$message.error('加载失败，请稍后重试');
    })
    .finally(() => {
      spinLoading.value = false;
    });
}

// 获取模板类型文本
function getTemplateTypeText(type) {
  const typeMap = {
    1: "购买合同",
    2: "出售合同",
    3: "转让合同"
  };
  return typeMap[type] || type;
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: "启用",
    0: "禁用"
  };
  return statusMap[status] || status;
}

// 获取字段类型文本
function getFieldTypeText(type) {
  const typeMap = {
    text: "文本",
    number: "数字",
    date: "日期",
    select: "下拉选择"
  };
  return typeMap[type] || type;
}

// 获取字段类型颜色
function getFieldTypeColor(type) {
  const colorMap = {
    text: "blue",
    number: "green",
    date: "orange",
    select: "purple"
  };
  return colorMap[type] || "gray";
}

// 获取日志点颜色
function getLogDotColor(type) {
  const colorMap = {
    create: "green",
    update: "blue",
    view: "gray",
    download: "orange"
  };
  return colorMap[type] || "gray";
}

// 预览PDF
function previewPdf() {
  if (templateInfo.pdfUrl) {
    pdfPreviewVisible.value = true;
  }
}

// 下载PDF
function downloadPdf() {
  if (templateInfo.pdfUrl) {
    // 模拟下载
    const link = document.createElement('a');
    link.href = templateInfo.pdfUrl;
    link.download = templateInfo.pdfFileName;
    link.click();
    
    proxy.$message.success('下载开始');
    
    // 记录下载日志
    operationLogs.value.unshift({
      id: Date.now(),
      type: "download",
      action: "下载PDF模板",
      operator: "当前用户",
      time: new Date().toLocaleString(),
      remark: ""
    });
  }
}

// 编辑
function onEdit() {
  emit("edit", {contractTemplateId: templateInfo.contractTemplateId});
}

// 返回
function onBack() {
  emit("back");
}
</script>

<style scoped>
.pdf-container {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  background-color: #f9fafb;
}

.pdf-thumbnail {
  max-width: 300px;
}

.pdf-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-pdf,
.empty-fields {
  padding: 40px 0;
  text-align: center;
}

:deep(.arco-descriptions-item-label) {
  font-weight: 500;
  color: var(--color-text-2);
}

:deep(.arco-descriptions-item-value) {
  color: var(--color-text-1);
}
</style>